import { DragEvent, Pen, App, PointerEvent } from 'leafer-ui';
import React, { memo, useEffect, useRef } from 'react';
import { useAtom } from 'jotai';
import {
  leaferAtom,
  isLeaferDragAtom,
  selectedBtnAtom,
  editorAtom,
  appAtom,
} from '../atoms';
import { rectDragEventStart, rectDragEventDrag } from '../penUtil';
import { Editor } from '@leafer-in/editor/src';

const LeaferCanvas: React.FC = memo(() => {
  const canvasDom = useRef(null);
  const [leafer, setLeafer] = useAtom(leaferAtom);
  const [isLeaferDrag] = useAtom(isLeaferDragAtom);
  const [selectedBtn, setSelectedBtn] = useAtom(selectedBtnAtom);
  const [editor, setEditor] = useAtom(editorAtom);
  const [app, setApp] = useAtom(appAtom);

  let pointX: number = 0;
  let pointY: number = 0;
  let penObj: Pen | null = null;

  useEffect(() => {
    if (canvasDom.current) {
      const app = new App({ view: canvasDom.current });
      const contentLayer = app.addLeafer({ fill: '#F9F7F7' });
      const editorLayer = app.addLeafer({ type: 'draw' });
      setApp(app);
      setLeafer(contentLayer);
     
      const editor = new Editor();
      editorLayer.add(editor);
      setEditor(editor);
    }
  }, []);

  useEffect(() => {
    app?.on(DragEvent.START, dragEventStart);
    app?.on(DragEvent.DRAG, dragEventDrag);
    app?.on(PointerEvent.DOWN, pointerEventTap)
    app?.on(DragEvent.END, dragEventEnd);

    return () => {
      app?.off(DragEvent.START, dragEventStart);
      app?.off(DragEvent.DRAG, dragEventDrag);
      app?.off(PointerEvent.DOWN, pointerEventTap);
      app?.off(DragEvent.END, dragEventEnd);
    };
  }, [selectedBtn, isLeaferDrag]);

  const dragEventStart = (e: DragEvent) => {
    console.log('e', e);
    console.log('selectedBtn', selectedBtn);
    console.log('isLeaferDrag', isLeaferDrag);
    if (isLeaferDrag) {
      if (selectedBtn === 'rectPen') {
        const [innerX, innerY, pen] = rectDragEventStart(e, leafer!);
        pointX = innerX;
        pointY = innerY;
        penObj = pen;
      }
    } 
  };

  const dragEventDrag = (e: DragEvent) => {
    if (isLeaferDrag) {
      if (selectedBtn === 'rectPen') {
        rectDragEventDrag(e, pointX, pointY, penObj!, editor!);
      }
    }
  };

  const dragEventEnd = (e: DragEvent) => {
    if (isLeaferDrag) {
      setSelectedBtn('');
    }
  }

  const pointerEventTap = (e: PointerEvent) => {
    if(e.target.tag === 'App') {
      editor!.target = null;
    } else if (e.target.tag === 'Path') {
      editor!.target = e.target as Pen;
    }
  }

  return <div className="h-full" ref={canvasDom}></div>;
});

export default LeaferCanvas;
